const express = require('express');
const router = express.Router();
const { Chapter,Course } = require('../../models')
const{ Op } = require('sequelize')
const {NotFoundError,success,failure} = require('../../utils/response')

//查询列表
router.get('/',async function(req, res, next) {
    try{
        const query = req.query
        //当前页数
        const currentPage = Math.abs(Number(query.currentPage))||1
        //每页显示条数
        const pageSize = Math.abs(Number(query.pageSize))||10 

        const offset = (currentPage-1)*pageSize


        if (!query.courseId) {
            throw new Error('获取章节列表失败，课程ID不能为空。');
          }
          
          const condition = {
            ...getCondition(),
            order: [['rank', 'ASC'], ['id', 'ASC']],
            limit: pageSize,
            offset: offset
          };
          
          condition.where = {
            courseId: {
              [Op.eq]: query.courseId
            }
          };
          
          if (query.title) {
            condition.where = {
              title: {
                [Op.like]: `%${ query.title }%`
              }
            };
          }
          

        const {count,rows} = await Chapter.findAndCountAll(condition)
        success(res,'查询列表成功',{
            chapters:rows,
            pagination:{
                total:count,
                currentPage:currentPage,
                pageSize:pageSize
            }
        },200)

    }catch(error){
        failure(res,error)
    }
    
});

//查询详情
router.get('/:id',async function(req, res, next) {
    try{
        const chapter = await getchapter(req)
        success(res,'查询成功',{ 
            chapter
        },201) 
    }catch(error){
        failure(res,error)
    }
    
});

//创建
router.post('/',async function(req, res, next) {
    try{
        //白名单过滤
        const body=filterBody(req)
        const chapter = await chapter.create(body)
        success(res,"创建成功",{chapter},201) 
    }catch(error){
        failure(res,error)
    }
    
});

//删除
router.delete('/:id',async function(req, res, next) {
    try{
        const chapter = await getchapter(req)
        success(res,"删除章节成功。",{chapter},200)
    }catch(error){
        failure(res,error)
    }
    
});

//更新
router.put('/:id',async function(req, res, next) {
    try{
        const chapter = await getchapter(req)
        const body = filterBody(req)
        await chapter.update(body)
        res.json({
            status:true,
            message:"更新章节成功",
            data:chapter
        })  
    }catch(error){
        res.status(500).json({
            status:false,
            message:"更新章节失败",
            errors:[error.message]
        })
    }
    
});

//公共方法：查询
async function getchapter(req){
    const {id} = req.params
    const condition = getCondition();
    //查询当前章节
    const chapter= await chapter.findByPk(id,condition)
    if(!chapter){
        throw new NotFoundError(`ID:${id}的章节未找到`)
    }
    return chapter
}

//白名单过滤
function filterBody(req){
    return{
        courseId: req.body.courseId,
        title: req.body.title,
        content: req.body.content,
        video: req.body.video,
        rank: req.body.rank
    }
}
function getCondition() {
    return {
      attributes: { exclude: ['CourseId'] },
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'name']
        }
      ]
    }
  }
module.exports = router;
